import re
from django.shortcuts import render, HttpResponse, redirect
from no_6.models import RBACPermission, RBACRole, RBACUser
from no_6.service.permission import initial_permission


# Create your views here.
def get_template_names(template_name):
    return 'no_6/pages/{}'.format(template_name)


def RBAClogin(request):
    if request.method == "POST":
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        user = RBACUser.objects.filter(name=username, pwd=pwd).first()
        if not user:
            return HttpResponse('用户不存在')

        # 验证身份
        request.session["user_id"] = user.pk
        initial_permission(user, request)
        return HttpResponse('登录成功')
    return render(request, get_template_names("rbac/login.html"))


# 查看用户
def RBACuser(request):
    # 获取session键值，如果不存在不报错，返回None
    permission_list = request.session.get('permission_list', [])
    # print(permission_list)
    path = request.path_info
    # print(path)
    # print(permission_list)
    # 下面的写法有点怪，全量匹配为啥要用啥正则
    # flag = False
    # for permission in permission_list:
    #     permission = "^%s$" % permission
    #     ret = re.match(permission, path)
    #     if ret:
    #         flag = True
    #         break
    # if not flag:
    #     return HttpResponse('无访问权限！')
    if not list(filter(lambda item: item == path, permission_list)):
        return HttpResponse('无访问权限！')
    return HttpResponse('查看用户成功')
